package com.hl233.framework.singleton;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.hl233.framework.utils.DruidUtil;
import org.springframework.beans.factory.annotation.Autowired;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @author 张振强15065206763
 * @create 2024-09-11
 */
public class ConnectionPool {

    private static ConnectionPool instance;
    private List<Connection> connections = new ArrayList<>();

    private static DruidDataSource ds;
    static {
        Properties properties =new Properties();
        InputStream is= DruidUtil.class.getResourceAsStream("/database.properties");
        try {
            properties.load(is);
            //创建连接池
            ds=(DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch ( Exception e) {
            e.printStackTrace();
        }
    }

    private ConnectionPool() {
        // 初始化连接池
        for (int i = 0; i < 10; i++) {
            Connection connection = createConnection();
            connections.add(connection);
        }
    }

    public static ConnectionPool getInstance() {
        if (instance == null) {
            instance = new ConnectionPool();
        }
        return instance;
    }

    public Connection getConnection() {
        // 从连接池中获取一个连接
        if (connections.size() > 0) {
            Connection connection = connections.remove(0);
            return connection;
        } else {
            throw new RuntimeException("No available connection in the pool.");
        }
    }

    public void releaseConnection(Connection connection) {
        // 释放连接，放回连接池
        connections.add(connection);
    }

    private Connection createConnection() {
        // 创建数据库连接
        Connection connection = null;
        //获取连接池对象
        try {
            connection = ds.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

}
